<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vuex</title>
    <script src="../node_modules/vue/dist/vue.js"></script>
    <script src="../node_modules/vuex/dist/vuex.js"></script>
</head>
<body>
    <div id="app">
        <h3>Vuex demo</h3>
        <p>{{ msg }}</p>
        
        <counter></counter>
    </div>

    <script>
        const store = new Vuex.Store({
            state: {
                count: 0,
                name: 'jack'
            },
            mutations: {
                increment(state, num) {
                    state.count += num;
                },
                update(state, uname) {
                    state.name = uname
                }
            },
            actions: {
                incrementA(context, num) {
                    context.commit("increment", num)
                }
            },
            getters: {
                uname(state) {
                    let r = Math.floor(Math.random() * 10);
                    return `hello ${state.name}`
                }
            }
        });
        const counter = {
            template: `
                <div>
                    <div>{{ count }}</div>
                    <div>{{ name }}</div>
                    <div>{{ uname }}</div>
                    <button @click="add">add</button>
                </div>
            `,
            computed: {
                count() {
                    return this.$store.state.count
                },
                name() {
                    return this.$store.state.name
                },
                uname() {
                    return this.$store.getters.uname
                }
            },
            methods: {
                add() {
                    // this.$store.commit("increment", 38)
                    // this.$store.commit("update", "倪大爷")
                    this.$store.dispatch("incrementA", 11);
                }
            }
        }
        new Vue({
            el: "#app",
            store: store,
            data: {
                msg: ''
            },
            components: {
                counter
            }
        })
    </script>
</body>
</html>